﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using ExportWordBibModule.SchemaImplementation;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;
using Author=ExportWordBibModule.SchemaImplementation.Author;

namespace ExportWordBibModule.Views
{
    /// <summary>
    /// Interaction logic for ExportWordBib.xaml
    /// </summary>
    public partial class ExportWordBib : UserControl
    {
        IDatabase _database;

        public ExportWordBib()
        {
            InitializeComponent();

            _database = Current.Container.Resolve<IDatabase>();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Sources sources = new Sources();

            IEnumerable<CatalogItem> items;
            using (UnitOfWork unitOfWork = _database.CreateUnitOfWork())
            {
                IRepository<CatalogItem> repository = new CatalogItemRepository(unitOfWork);
                items = repository.All;


                foreach (var item in items)
                {
                    Source source = new Source();
                    source.BookTitle = item.Title;
                    foreach (var author in item.Authors)
                    {
                        Author eAuthor = new Author();
                        eAuthor.First = author.FirstName;
                        eAuthor.Last = author.LastName;
                        source.Authors.Add(eAuthor);
                    }

                    sources.Source.Add(source);
                }
            }

            var s = sources.Render();

            using(StreamWriter writer = new StreamWriter(exportPath.Text, false, Encoding.UTF8))
            {
                writer.Write(s);
            }

            
        }
    }
}
